/*
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package botobjects;

import interfaces.BotObject;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.jibble.pircbot.Colors;

import tools.StringTools;
import database.DBConnectionFactory;

/**
 * Represents a Discussion
 * 
 * 
 */
public class Discussion implements BotObject {
   /**
    * Removes a discussion
    * 
    * @param args
    *           specifies the id of the discussion to be removed
    * @return true if the discussion was successfully deleted
    */
   public static boolean deleteFromDB(final String... args) {
	  boolean out = false;
	  if (args.length < 1)
		 return out;
	  PreparedStatement ps = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("DELETE FROM discussion WHERE id = ?");
		 ps.setInt(1, Integer.parseInt(args[0]));
		 if (ps.executeUpdate() == 1) {
			out = true;
		 }
	  } catch (SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   /**
    * Returns a list of all the current discussions
    * 
    * @param isAdmin
    *           Used to determine whether private (admin only) discussions should be included
    * @return a List of Discussion objects
    */
   public static List<Discussion> getDiscussions(final boolean isAdmin) {
	  List<Discussion> out = new LinkedList<Discussion>();
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  try {
		 if (isAdmin) {
			ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("SELECT * FROM discussion");
		 } else {
			ps = DBConnectionFactory.getConnectionHandler().getConnection()
				  .prepareStatement("SELECT * FROM discussion WHERE private = false");
		 }
		 rs = ps.executeQuery();
		 while (rs.next()) {
			out.add(new Discussion(rs.getInt("id"), rs.getString("title"), rs.getBoolean("private"), rs.getBoolean("locked")));
		 }
	  } catch (SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   /**
    * Locks a discussion so that non-admin users cannot post in it
    * 
    * @param discussionID
    * @param lock
    *           true to lock, false to unlock
    * @return true if the locking/unlocking succeeds
    */
   public static boolean lockDiscussion(final int discussionID, final boolean lock) {
	  boolean out = false;
	  PreparedStatement ps = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection()
			   .prepareStatement("UPDATE discussion SET locked = ? WHERE id = ?");
		 ps.setBoolean(1, lock);
		 ps.setInt(2, discussionID);
		 if (ps.executeUpdate() == 1) {
			out = true;
		 }
	  } catch (SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   private int id = 0;

   private String title = "";

   private boolean adminOnly = false;

   private boolean locked = false;

   public Discussion(final int id, final String title, final boolean adminOnly, final boolean locked) {
	  this.id = id;
	  this.title = title;
	  this.adminOnly = adminOnly;
	  this.locked = locked;
   }

   public int getId() {
	  return id;
   }

   @Override
   public List<String> getIRCOutput(final int outputType, final String... args) {
	  List<String> out = new LinkedList<String>();
	  if (StringTools.isNullOrEmpty(getTitle()))
		 return out;
	  out.add(Colors.OLIVE + "ID: " + Colors.BLUE + getId() + " " + Colors.OLIVE + "Title: " + Colors.BLUE + getTitle()
			+ (isLocked() ? Colors.RED + " LOCKED" : ""));
	  return out;
   }

   @Override
   public Map<String, Object> getRPCOutput(final int... includes) {
	  Map<String, Object> out = new HashMap<String, Object>();
	  if (StringTools.isNullOrEmpty(getTitle()))
		 return out;
	  out.put("ID", getId());
	  out.put("Title", getTitle());
	  out.put("Admin Only", isAdminOnly());
	  out.put("Locked", isLocked());
	  return out;
   }

   public String getTitle() {
	  return title;
   }

   public boolean isAdminOnly() {
	  return adminOnly;
   }

   public boolean isLocked() {
	  return locked;
   }

   @Override
   public boolean saveToDB() {
	  boolean out = false;
	  if (StringTools.isNullOrEmpty(getTitle()))
		 return out;
	  PreparedStatement ps = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection()
			   .prepareStatement("INSERT INTO discussion VALUES(default,?,?,?)");
		 ps.setString(1, getTitle());
		 ps.setBoolean(2, isAdminOnly());
		 ps.setBoolean(3, isLocked());
		 if (ps.executeUpdate() == 1) {
			out = true;
		 }
	  } catch (SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   public void setAdminOnly(final boolean adminOnly) {
	  this.adminOnly = adminOnly;
   }

   public void setLocked(final boolean locked) {
	  this.locked = locked;
   }
}
